import 'package:flutter/material.dart';
import 'package:manual/getxs/cart_controller.dart';

import 'package:get/get.dart';

class CartPage extends StatelessWidget {
  final CartController controller = Get.put(CartController());
  CartPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('购物车')),
      body: Column(
        children: [
          Expanded(
            child: Obx(() => ListView.builder(
                  itemCount: controller.cartList.length,
                  itemBuilder: (context, index) {
                    final item = controller.cartList[index];
                    return ListTile(
                      title: Text('商品ID: ${item.id}'),
                      subtitle: Obx(() => Text('数量: ${item.count.value}, 单价: ${item.price}')),
                      trailing: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          // 减少数量按钮
                          IconButton(
                            icon: const Icon(Icons.remove),
                            onPressed: () {
                              if (item.count > 1) {
                                controller.updateItemCount(item.id, item.count.value - 1);
                              } else {
                                // 如果数量减少到 0，移除商品
                                controller.removeItem(item.id);
                              }
                            },
                          ),
                          // 增加数量按钮
                          IconButton(
                            icon: const Icon(Icons.add),
                            onPressed: () {
                              controller.updateItemCount(item.id, item.count.value + 1);
                            },
                          ),
                          // 删除商品按钮
                          IconButton(
                            icon: const Icon(Icons.delete),
                            onPressed: () {
                              controller.removeItem(item.id);
                            },
                          ),
                        ],
                      ),
                    );
                  },
                )),
          ),
          Obx(() => Padding(
                padding: const EdgeInsets.all(16.0),
                child: Text(
                  '总价格: ￥${controller.totalPrice.value.toStringAsFixed(2)}',
                  style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
              )),
        ],
      ),
    );
  }
}
